/**
 * VaxjoWeather.java
 * Created: May 9, 2010
 * Jonas Lundberg, LnU
 */

package com.example.firstassignment;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import android.app.ListActivity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;

/**
 * This is a first prototype for a weather app. It is currently 
 * only downloading weather data for Växjö. 
 * 
 * This activity downloads weather data and constructs a WeatherReport,
 * a data structure containing weather data for a number of periods ahead.
 * 
 * The WeatherHandler is a SAX parser for the weather reports 
 * (forecast.xml) produced by www.yr.no. The handler constructs
 * a WeatherReport containing meta data for a given location
 * (e.g. city, country, last updated, next update) and a sequence 
 * of WeatherForecasts.
 * Each WeatherForecast represents a forecast (weather, rain, wind, etc)
 * for a given time period.
 * 
 * The next task is to construct a list based GUI where each row 
 * displays the weather data for a single period.
 * 
 *  
 * @author jlnmsi
 *
 */

public class VaxjoWeather extends ListActivity {
	private InputStream input;
	private WeatherReport report = null;
	
	private List<String> mainList = new ArrayList<String>();
		
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        try {
        	URL url = new URL("http://www.yr.no/sted/Sverige/Kronoberg/V%E4xj%F6/forecast.xml");
        	AsyncTask task = new WeatherRetriever().execute(url);
        } catch (IOException ioe ) {
    		ioe.printStackTrace();
    	}
        
    }
    private void setup_weatherforcast(){
    	if(this.report != null){

    		System.out.println(report);

    		for (WeatherForecast forecast : report) {
    			
    			String temp	= "Temperature: "+forecast.getTemp()+"C";
    			mainList.add(temp);
    			
    		}
    	}
    	
    	
    	setListAdapter(new MultiAdapter(this));
    	
    	/* Attach list item listener */
        ListView lv = getListView();
        lv.setOnItemClickListener(new OnItemClick()); 
    }
    private class OnItemClick implements OnItemClickListener {
    	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    		
    		WeatherForecast forecast  = report.getForecast(position);
    		TextView st = (TextView)view.findViewById(R.id.smallText);

    		
    		if( !(st.getText().toString().contains("Rain")) ){
    			st.setText("Rain: "+forecast.getRain() + "mm"+"\n"+forecast.getWindSpeedName()+": "+forecast.getWindSpeed()+"m/s"+",\n"+"Wind direction: "+forecast.getWindDirection());
    		}
    		else {
    			st.setText(forecast.getStartYYMMDD()+"\n"+forecast.getStartHHMM()+"-"+forecast.getEndHHMM() );
    		}
    	}   	
    }
    
    class MultiAdapter  extends ArrayAdapter<String> {
    	public MultiAdapter(Context context) {
    		super(context,R.layout.detailed_information, mainList);
    	}
    	
    	@Override   // Called when updating the ListView
    	public View getView(int position, View convertView, ViewGroup parent) {
    		View row;
    		WeatherForecast forecast  = report.getForecast(position);
    		if (convertView == null) {	// Create new row view object   		
    			LayoutInflater inflater = getLayoutInflater();
    			row = inflater.inflate(R.layout.detailed_information,parent,false);
    		}
    		else    // reuse old row view to save time/battery
    			row = convertView;
    		
    		/* Add new data to row object */
    		TextView lt = (TextView)row.findViewById(R.id.largeText);
    		lt.setText(mainList.get(position));
    		
    		ImageView iv = (ImageView)row.findViewById(R.id.image);
    		iv.setBackgroundResource(setIcon(position));
    		
    		
    		TextView st = (TextView)row.findViewById(R.id.smallText);
    		st.setText(forecast.getStartYYMMDD()+"\n"+forecast.getStartHHMM()+"-"+forecast.getEndHHMM());
    		
    		return row;		
    	}
    }
    
   private int setIcon(int position){
	   int image = R.drawable.twelve; /*default*/
	   int weathercode = report.getForecast(position).getWeatherCode();
	   int timeperiod = report.getForecast(position).getPeriodCode();
	   
	   if( ( timeperiod ==  0 ) || ( timeperiod == 3 ) ){ /* Night */
		   switch( weathercode ){
		   case 1:
			   image = R.drawable.onen;
			   break;
		   case 2:
			   image = R.drawable.twon;
			   break;
		   case 3:
			   image = R.drawable.threen;
			   break;
		   case 4:
			   image = R.drawable.four;
			   break;
		   case 5:
			   image = R.drawable.fiven;
			   break;
		   case 6:
			   image = R.drawable.sixn;
			   break;
		   case 7:
			   image = R.drawable.sevenn;
			   break;
		   case 8:
			   image = R.drawable.eightn;
			   break;
		   case 9:
			   image = R.drawable.nine;
			   break;
		   case 10:
			   image = R.drawable.ten;
			   break;
		   case 11:
			   image = R.drawable.eleven;
			   break;
		   case 12:
			   image = R.drawable.twelve;
			   break;
		   case 13:
			   image = R.drawable.thirteen;
			   break;
		   case 14:
			   image = R.drawable.fourteen;
			   break;
		   case 15:
			   image = R.drawable.fithteen;
			   break;
		   }
	   }else{ /* Day */
		
		   switch( weathercode ){
		   case 1:
			   image = R.drawable.oned;
			   break;
		   case 2:
			   image = R.drawable.twod;
			   break;
		   case 3:
			   image = R.drawable.threed;
			   break;
		   case 4:
			   image = R.drawable.four;
			   break;
		   case 5:
			   image = R.drawable.fived;
			   break;
		   case 6:
			   image = R.drawable.sixd;
			   break;
		   case 7:
			   image = R.drawable.sevend;
			   break;
		   case 8:
			   image = R.drawable.eightd;
			   break;
		   case 9:
			   image = R.drawable.nine;
			   break;
		   case 10:
			   image = R.drawable.ten;
			   break;
		   case 11:
			   image = R.drawable.eleven;
			   break;
		   case 12:
			   image = R.drawable.twelve;
			   break;
		   case 13:
			   image = R.drawable.thirteen;
			   break;
		   case 14:
			   image = R.drawable.fourteen;
			   break;
		   case 15:
			   image = R.drawable.fithteen;
			   break;
		   }
	   }
	   return image;
   }
    
    
    private void PrintReportToConsole() {
    	if (this.report != null) {
        	/* Print location meta data */ 
        	System.out.println(report);
        	
        	/* Print forecasts */
    		int count = 0;
    		for (WeatherForecast forecast : report) {
    			count++;
    			System.out.println("Forecast "+count);
    			System.out.println( forecast.toString() );
    		}
    	}
    	else {
    		System.out.println("Weather report has not been loaded.");
    	}
    }
    
    private class WeatherRetriever extends AsyncTask<URL, Void, WeatherReport> {
    	protected WeatherReport doInBackground(URL... urls) {
    		try {
    			return WeatherHandler.getWeatherReport(urls[0]);
    		} catch (Exception e) {
    			throw new RuntimeException(e);
    		} 
    	}

    	protected void onProgressUpdate(Void... progress) {

    	}

    	protected void onPostExecute(WeatherReport result) {
    		report = result;
    		setup_weatherforcast();
//    		PrintReportToConsole();
//    		AddToList();
    	}
    }
}